from time import sleep
import csv
from PySide2.QtCore import QThread, Signal

import pandas as pd
from pandas import DataFrame

from analysis import t_merge_sensor_data, get_start_value, calculate_bend_degree
from public import Skt, PublicData
from db.tb_tread import add_measure_data, add_treated_data, add_sensor_start_degree
from ui_func import start_df_mean_to_sensor


class Th_Base(QThread):
    # 搜索进度
    signal_send = Signal(object)

    # 搜索完成

    def __init__(self, parent=None) -> None:
        super().__init__(parent)
        self.is_running = True

    def stop(self):
        self.is_running = False
        self.terminate()


class Th_sensor_search(Th_Base):
    """
    搜索的打开的传感器，搜索10次 获取搜索到的传感器代码，反馈给主程序
    """

    def __init__(self, parent=None, count=50, seconds=5) -> None:
        super().__init__(parent)
        self.is_running = True
        self.count = count
        self.seconds = seconds
        self.sleep_time = self.seconds / self.count

    def run(self):
        skt = Skt()
        progress_base = 100 / self.count
        for i in range(self.count):
            skt.send_broadcast_for_sensor()
            sleep(self.sleep_time)
            self.signal_send.emit(int(i * progress_base))
        self.signal_send.emit(100)


class Th_get_sonsor_data(Th_Base):
    def __init__(self, parent=None):
        super().__init__(parent)
        self.skt = Skt()

    def run(self):
        while self.is_running:
            data = self.skt.get_sensor_data()
            if data:
                self.signal_send.emit(data)


class Th_analysis_data(Th_Base):
    def __init__(self, parent=None) -> None:
        super().__init__(parent)

    def run(self):
        public_data = PublicData()
        data_col_list = public_data.sensor_data_col

        public_data.has_start_record
        first_recode_df = None
        i = 0
        while public_data.data_read_signal:
            # 获取传感器的值
            data_list = public_data.queue_sensor_data.get()
            if data_list:
                # 将获取的数据转为DataFrame
                df_data_list = DataFrame(data_list, columns=data_col_list)
                # 处理数据
                df_treated_data = t_merge_sensor_data(df_data_list)
                # 将处理后的数据在数据表中显示
                self.signal_send.emit({"label": "show_data", "data": df_treated_data})
                product_name = public_data.product.name if public_data.product else ""
                # 开始记录数据                   
                if public_data.data_save_signal:
                    # 保证传感器稳定，获取初始值                    
                    if public_data.has_start_record:

                        writer = None
                        # with open(f'{product_name}_output.csv', 'a', newline='') as csvfile:
                        #     writer = csv.writer(csvfile)
                        #     writer.writerow(["sensor_id", "start_x", "start_y", "start_z", "end_x", "end_y", "end_z",
                        #                      "cross_agree"])
                        bend_agree_dic = calculate_bend_degree(df_treated_data,  writer)
                        # public_data.sensor_bend_dict_queue.put(bend_agree_dic)
                        # 计算变化的角度
                        self.signal_send.emit({"label": "bend_value", "data": bend_agree_dic})

                    else:
                        # 获取初始角度值  

                        # 获取10个传感器处理后的平均数据                     
                        first_recode_df = pd.concat(objs=(first_recode_df, df_treated_data))
                        if i > 10:

                            df_start_mean = get_start_value(first_recode_df)
                            if type(df_start_mean) is DataFrame:
                                df_start_mean["product_id"] = public_data.product.id
                                public_data.has_start_record = True
                                public_data.df_start_mean = df_start_mean
                                start_df_mean_to_sensor(public_data.df_start_mean)
                                add_sensor_start_degree(df_start_mean)

                            else:  # 如果计算值不合格，重新取值计算
                                first_recode_df = None
                                i = 0
                        else:
                            i += 1
                    add_measure_data(df_data_list)
                    add_treated_data(df_treated_data)
                else:
                    first_recode_df = df_treated_data




